package com.bhlc.es.bhlc.util;

import com.bhlc.es.bhlc.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:luocheng5
 * @DATE: 2020/11/10 22:49
 */
public class HtmlParseUtil {
    public static void main(String[] args) throws Exception {
        new HtmlParseUtil().paresJD("vue").forEach(System.out::println);

    }

    public List<Content> paresJD(String keywords) throws Exception {
        //获取请求
        String url = "https://search.jd.com/Search?keyword="+keywords+"&enc=utf-8";
        //解析网页 js页面对象
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList = new ArrayList<>();
        for (Element el : elements) {
            String image = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
//                System.out.println("=========================");
//                System.out.println(image);
//                System.out.println(price);
//                System.out.println(title);
            Content content = new Content();
            content.setImg(image);
            content.setPrice(price);
            content.setTitle(title);
            goodsList.add(content);

        }
        return goodsList;
    }
}
